﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace VLog
{
    /// <summary>
    /// XML 日志
    /// </summary>
    public class XmlVLog : VLogBase
    {

        public XmlDocument xmlDocument = null;

        public XmlVLog()
        {
            this.Path = LogCommons.GetPath(PathType.Xml);
            if (!File.Exists(this.Path))
            {
                ReCreate(this.Path);
            }
            this.xmlDocument = new XmlDocument();
            this.xmlDocument.Load(this.Path);
        }

        static void ReCreate(string path)
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlDeclaration xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", null);
            xmlDocument.AppendChild(xmldecl);
            XmlElement ele = xmlDocument.CreateElement("root");
            xmlDocument.AppendChild(ele);
            xmlDocument.Save(path);
        }

        protected override bool Write(VLogEntity entity)
        {
            XmlElement ele = this.xmlDocument.CreateElement("item");
            ele.InnerXml = string.Format(
                                        @"<Senders>{0}</Senders>
                                        <Content>{1}</Content>
                                        <Date>{2}</Date>
                                        <Level>{3}</Level>
                                        "               , base.GetSenders()
                                                        , entity.FullInfo
                                                        , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")
                                                        , entity.Level
              );
            this.xmlDocument.DocumentElement.AppendChild(ele);
            xmlDocument.Save(this.Path);
            return true;
        }
    }
}
